//
//  ViewController.swift
//  testDemo
//
//  Created by 张彦辉 on 2017/8/13.
//  Copyright © 2017年 张彦辉. All rights reserved.
//

import UIKit
import Pastel
import SwiftyJSON
import Kingfisher


class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource{

    var table:UITableView!
    var movies:[Movie]!
    let refreshControl = UIRefreshControl()
    var pageNum = 1
    var isLoadData = false
    override func viewDidLoad() {
        super.viewDidLoad()
        
        table = UITableView(frame: CGRect(x: 0, y: 64, width: self.view.frame.width, height: self.view.frame.height-114))
        table.dataSource = self
        table.delegate = self
        table.backgroundColor = UIColor.clear
        table.separatorColor = UIColor.gray
    
        self.view.addSubview(table)
        let pastelView = PastelView(frame: self.view.frame)
        pastelView.startAnimation()
        self.view.insertSubview(pastelView, at: 0)
        refreshControl.addTarget(self, action: #selector(loadData), for: .valueChanged)
        refreshControl.attributedTitle = NSAttributedString(string: "松开后自动刷新")
        table.addSubview(refreshControl)
        loadData()
        
    }
    
    
    
    func loadData() {
        if !isLoadData {
            isLoadData = true
            pageNum = 1
            Network.getMovies(param: ["pageNum":pageNum]) { (movies,hasNext) in
                self.movies = movies
                self.table.reloadData()
                self.refreshControl.endRefreshing()
                self.isLoadData = false
            }
        }
        
        
    }
    func nextData() {
        pageNum += 1
        print(pageNum)
        Network.getMovies(param: ["pageNum":pageNum]) { (movies,hasNext) in
            self.movies.append(contentsOf: movies)
            self.table.reloadData()
            self.isLoadData = false
            
        }
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

// MARK: -- UITableView
extension ViewController{
    
    
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        let offset = scrollView.contentOffset.y
        let contentHeight = scrollView.contentSize.height
        let screenHeight = self.view.frame.height
        if !isLoadData && (offset + screenHeight >= contentHeight) {
            isLoadData = true
            nextData()
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if movies != nil {
            return movies.count
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cellId")
        if cell == nil {
            cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cellId")
        }
        let mov = movies[indexPath.row]
        cell!.textLabel?.text = mov.name
        let url = URL(string: mov.image)
        cell?.imageView?.kf.setImage(with: url, placeholder: UIImage(named: "a"))
        cell!.accessoryType = .disclosureIndicator
        
        let size = CGSize(width: 40, height: 40)
        UIGraphicsBeginImageContextWithOptions(size, false, 1)
        
        let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
        cell?.imageView?.image?.draw(in: rect)
        cell?.imageView?.image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return cell!
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60.0
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let view2 = View2Controller()
        view2.movie = movies[indexPath.row]
        self.navigationController?.pushViewController(view2, animated: true)
    }
    
}

